package com.easyCode.mysql.sqlBuilder.sqlInfo;
import com.easyCode.mysql.constants.MysqlFiledTypeConstants;
import com.easyCode.sqlBuilder.sqlInfo.BaseFiledSqlInfo;
import com.easyCode.sqlBuilder.sqlUtil.SqlBuildUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.Ordered;


/**
 * 提供字段sql语句相关信息
 *
 * @author zdh
 */
@Data
public class MysqlFiledSqlInfo extends BaseFiledSqlInfo implements Ordered {
    private final CharsetSqlInfo charsetSqlInfo=CharsetSqlInfo.getDefault();

    /**
     * 只针对varchar和char类型添加字符集和排序规则
     */
    private String wrapperCharsetIfNeeded(String filedType) {
        if (filedType.equalsIgnoreCase(MysqlFiledTypeConstants.VARCHAR) || filedType.equalsIgnoreCase(MysqlFiledTypeConstants.CHAR)) {
            return charsetSqlInfo.buildSql();
        }
        return "";
    }

    /**
     * 如果当前字段类型是日期类型,那么defaultVal不需要加上双引号
     */
    private String wrapperDefaultValIfNeeded(Object defaultVal) {
        if(filedType.equalsIgnoreCase(MysqlFiledTypeConstants.DATA_TIME)){
            return String.valueOf(defaultVal);
        }
        return SqlBuildUtil.wrapSqlVal((String) defaultVal);
    }

    /**
     * @return 根据自身掌握的sql信息构建出一部分或者完整的sql语句
     */
    @Override
    public String doBuildSql() {
        return SqlBuildUtil.buildSql(SqlBuildUtil.wrapSqlParam(filedName),
                SqlBuildUtil.buildFiledType(filedType, filedLen),
                wrapperCharsetIfNeeded(filedType),
                SqlBuildUtil.assembleIfNeed(notNull, "NOT NULL"),
                SqlBuildUtil.assembleIfNeed(defaultVal, "DEFAULT " + wrapperDefaultValIfNeeded(defaultVal)),
                SqlBuildUtil.assembleIfNeed(autoIncrement, "AUTO_INCREMENT"),
                SqlBuildUtil.assembleIfNeed(comment, "COMMENT " + SqlBuildUtil.wrapSqlVal(comment)));
    }


}
